package com.jinkaimen.kqb.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.base.BaseFragment;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.AppAesUtil;
import com.ht.baselibs.utils.ChannelUtils;
import com.ht.baselibs.utils.DeviceUtils;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.igexin.sdk.PushManager;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.bean.ConsultBean;
import com.jinkaimen.kqb.dao.AccountDao;
import com.jinkaimen.kqb.factory.FragmentFactory;
import com.jinkaimen.kqb.http.ConsultInterceptor;
import com.jinkaimen.kqb.manager.ApiManager;
import com.jinkaimen.kqb.service.GetuiService;
import com.jinkaimen.kqb.service.PushService;
import com.jinkaimen.kqb.ui.fragment.GetMoneyFragment;
import com.jinkaimen.kqb.ui.fragment.h5toapp.HomeFragment;
import com.jinkaimen.kqb.utils.AppUtils;
import com.jinkaimen.kqb.utils.URLUtils;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

import static com.jinkaimen.kqb.http.ConsultInterceptor.CONSULT_SERVICE_CODE;
import static com.jinkaimen.kqb.http.ConsultInterceptor.privateKey;

public class HomeActivity extends BaseActivity {
    private long exitTime;
    private TextView mHomeTabView;
    private TextView mSelfTabView;
    private TextView mTabGetMoney;
    private TextView mTabShare;
    private TextView mTabNotify;
    private ImageView mIvShareRedHint;
    private ImageView mIvNotifyRedHint;
    private LinearLayout mLgHomeTab;
    private static final int REQUEST_PERMISSION = 0;

    @Override
    protected boolean hasEvent() {
        return true;
    }

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PackageManager pkgManager = getPackageManager();

//        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
//        boolean sdCardWritePermission =
//                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
                REQUEST_PERMISSION);
    }


    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("酷钱包")
                .setLeftBtnVisibility(View.GONE);
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_home;
    }

    @Override
    protected void initChildView() {
        mHomeTabView = (TextView) findViewById(R.id.rb_home_tab_home);
        mSelfTabView = (TextView) findViewById(R.id.rb_home_tab_self);
        mTabGetMoney = (TextView) findViewById(R.id.rb_home_tab_get_money);
        mTabShare = (TextView) findViewById(R.id.rb_home_tab_share);
        mTabNotify = (TextView) findViewById(R.id.rb_home_tab_notify);
        mIvShareRedHint = (ImageView) findViewById(R.id.iv_share_red_hint);
        mIvNotifyRedHint = (ImageView) findViewById(R.id.iv_notify_red_hint);
        mLgHomeTab = (LinearLayout) findViewById(R.id.rg_home_tab);
        resetTab();
        mHomeTabView.setSelected(true);
        mHomeTabView.setTextColor(getResources().getColor(R.color.color_05));
        switchFragment(FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB0), R.id.fl_activity_home_content);
    }

    @Override
    protected void initChildData() {
        // TODO: 2017/8/14 请求接口拿到是否要显示红点
//        mIvShareRedHint.setVisibility(View.VISIBLE);
//        mIvNotifyRedHint.setVisibility(View.VISIBLE);

    }

    @Override
    protected void setChildViewListener() {
        mHomeTabView.setOnClickListener(this);
        mSelfTabView.setOnClickListener(this);
        mTabGetMoney.setOnClickListener(this);
        mTabShare.setOnClickListener(this);
        mTabNotify.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        BaseFragment baseFragment = null;
        switch (v.getId()) {
            case R.id.rb_home_tab_home:
                resetTab();
                mHomeTabView.setSelected(true);
                mHomeTabView.setTextColor(getResources().getColor(R.color.color_16));
                mTitleBarView.setTitleText("酷钱包").setLeftBtnVisibility(View.GONE);
                baseFragment = FragmentFactory.getHomeTabFragment(0);
                switchFragment(baseFragment, R.id.fl_activity_home_content);
                break;

            case R.id.rb_home_tab_get_money:
                if (!AppUtils.isLogin()) {
                    ActivityUtils.startActivity(HomeActivity.this, LoginActivity.class);
                    return;
                }
                resetTab();
                mLgHomeTab.setVisibility(View.GONE);
                mTitleBarView.setTitleText("赚钱").setLeftBtnVisibility(View.GONE).setLeftBtnClearVisibility(View.VISIBLE).setOnLeftBtnClearClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EventBus.getDefault().post(new EventCenter(EventCode.GET_MONEY_GO_BACK));
                    }
                });

                mTabGetMoney.setSelected(true);
                mTabGetMoney.setTextColor(getResources().getColor(R.color.color_16));
                baseFragment = FragmentFactory.getHomeTabFragment(1);
                switchFragment(baseFragment, R.id.fl_activity_home_content);
                break;
            case R.id.rb_home_tab_share:
                if (!AppUtils.isLogin()) {
                    ActivityUtils.startActivity(HomeActivity.this, LoginActivity.class);
                    return;
                }
                resetTab();
                mTitleBarView.setTitleText("分享").setLeftBtnVisibility(View.GONE);
                mTabShare.setSelected(true);
                mTabShare.setTextColor(getResources().getColor(R.color.color_16));
                baseFragment = FragmentFactory.getHomeTabFragment(2);
                switchFragment(baseFragment, R.id.fl_activity_home_content);
                break;
            case R.id.rb_home_tab_notify:
                if (!AppUtils.isLogin()) {
                    ActivityUtils.startActivity(HomeActivity.this, LoginActivity.class);
                    return;
                }
                resetTab();
                mTitleBarView.setTitleText("消息").setLeftBtnVisibility(View.GONE);
                mTabNotify.setSelected(true);
                mTabNotify.setTextColor(getResources().getColor(R.color.color_16));
                baseFragment = FragmentFactory.getHomeTabFragment(3);
                switchFragment(baseFragment, R.id.fl_activity_home_content);
                break;
            case R.id.rb_home_tab_self:
                if (!AppUtils.isLogin()) {
                    ActivityUtils.startActivity(HomeActivity.this, LoginActivity.class);
                    return;
                }
                resetTab();
                mTitleBarView.setTitleText("我的").setLeftBtnVisibility(View.GONE);
                mSelfTabView.setSelected(true);
                mSelfTabView.setTextColor(getResources().getColor(R.color.color_16));
                baseFragment = FragmentFactory.getHomeTabFragment(4);
                switchFragment(baseFragment, R.id.fl_activity_home_content);
                break;
        }
    }

    @Override
    protected void onEvent(int code, Object data) {
        switch (code) {
            case EventCode.EVENT_CODE_START_LOGOUT:
                resetTab();
                mHomeTabView.setSelected(true);
                mHomeTabView.setTextColor(getResources().getColor(R.color.color_16));
                mSelfTabView.setTextColor(getResources().getColor(R.color.black9));
                mTitleBarView.setTitleText("酷钱包");
                BaseFragment baseFragment = FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB0);
                switchFragment(baseFragment, R.id.fl_activity_home_content);
                break;
            case EventCode.EVENT_CODE_GETUI_LINE:
                break;
            case EventCode.EVENT_CODE_SHARE_RED_HINT_SHOW:
                mIvShareRedHint.setVisibility(View.GONE);
                break;
            case EventCode.EVENT_CODE_NOTIFY_RED_HINT_SHOW:
                mIvNotifyRedHint.setVisibility(View.GONE);
                break;
            case EventCode.EVENT_CODE_FINISH_ACTIVITY:
                checkFinishApp((KeyEvent) data);
                break;
            case EventCode.GET_MONEY_GO_BACK:
                resetTab();
                mHomeTabView.setSelected(true);
                mHomeTabView.setTextColor(getResources().getColor(R.color.color_16));
                mTitleBarView.setTitleText("酷钱包").setLeftBtnVisibility(View.GONE);
                baseFragment = FragmentFactory.getHomeTabFragment(0);
                switchFragment(baseFragment, R.id.fl_activity_home_content);
                break;


            case EventCode.HSY_REQUEST_CODE_EXPIRE://登陆超时
                int retryTimes = 0;
                String token = SharedPreferencesUtils.getString(ConsultInterceptor.ACCESS_TOKEN, "");
                while (TextUtils.isEmpty(token) && retryTimes++ < 3) {
                    try {
//                    MessageDigest messageDigest= MessageDigest.getInstance("MD5");
//                    String checkMd5 = Utils.byte2hex(messageDigest.digest(check.getBytes()));
                        Map<String, Object> map = new HashMap<>();
                        map.put("deviceId", DeviceUtils.getDeviceId());
                        map.put("deviceName", DeviceUtils.getDeviceName());
                        map.put("osVersion", DeviceUtils.getOsVersion());
                        map.put("appCode", "hss");
                        map.put("appVersion", DeviceUtils.getAppVersionName());
                        map.put("appChannel", ChannelUtils.getChannel());

                        String datas = URLEncoder.encode(AppAesUtil.encryptCBC_NoPaddingToBase64String(JSON.toJSONString(map, false),
                                "utf-8", privateKey.substring(0, 16), privateKey.substring(16, 32)), "utf-8");

                        retrofit2.Response<ResponseBody> consultCall = ApiManager
                                .getApi()//
                                .consult(
                                        CONSULT_SERVICE_CODE,
                                        datas
                                )//
                                .execute();

                        LogUtils.error(AppAesUtil.decryptCBC_NoPaddingFromBase64String(datas,
                                "utf-8", privateKey.substring(0, 16), privateKey.substring(16, 32)));

                        if (consultCall.isSuccessful()) {
                            String result = consultCall.body().string();
                            BaseGetBean baseGetBean = JSON.parseObject(result, BaseGetBean.class);
                            ConsultBean consultBean = JSON.parseObject(baseGetBean.encryptDataResult, ConsultBean.class);
                            SharedPreferencesUtils.put(ConsultInterceptor.ACCESS_TOKEN, consultBean.accessToken);
                            SharedPreferencesUtils.put(ConsultInterceptor.ENCRYPT_KEY, consultBean.encryptKey);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        break;
                    }
                }
                ApiManager.getApi().logout(
                        "HSY001018"
                ).enqueue(new NetCallBack<String>() {
                    @Override
                    protected void onSuccess(Call<String> call, Response<String> response) {
                        AppUtils.logout();
                        AccountDao.getInstance().clear();
                        SharedPreferencesUtils.put("master_shop_id", "");
                        SharedPreferencesUtils.put("real_name", "");
                        SharedPreferencesUtils.put("alipayRate", "");
                        SharedPreferencesUtils.put("weixinRate", "");
                        SharedPreferencesUtils.put("shop_name", "");
                        EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_BALANCE_CHANGE));
                        EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_START_LOGOUT));
                        ActivityUtils.startActivity(HomeActivity.this, LoginActivity.class);
                    }

                    @Override
                    protected void hiddenProgress() {
                        HomeActivity.this.hideLodingDialog();
                    }

                    @Override
                    protected boolean isNullNeedCallback() {
                        return true;
                    }
                });
                break;
            case EventCode.HSY_REQUEST_CODE_UNLOGIN://用户未登陆

                break;
        }
    }

    private void resetTab() {
        mHomeTabView.setSelected(false);
        mSelfTabView.setSelected(false);
        mTabGetMoney.setSelected(false);
        mTabShare.setSelected(false);
        mTabNotify.setSelected(false);
        mTabGetMoney.setTextColor(getResources().getColor(R.color.black9));
        mHomeTabView.setTextColor(getResources().getColor(R.color.black9));
        mSelfTabView.setTextColor(getResources().getColor(R.color.black9));
        mTabShare.setTextColor(getResources().getColor(R.color.black9));
        mTabNotify.setTextColor(getResources().getColor(R.color.black9));
        mLgHomeTab.setVisibility(View.VISIBLE);
        mTitleBarView.setLeftBtnClearVisibility(View.GONE);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {

            Fragment mCurrentFragment = getVisibleFragment();
            if (mCurrentFragment instanceof GetMoneyFragment) {
                ((GetMoneyFragment) mCurrentFragment).onKeyDown(event);
                return true;
            }
            if (mCurrentFragment instanceof HomeFragment) {
                ((HomeFragment) mCurrentFragment).onKeyDown(event);
                return true;
            }
            return false;
        }
        return super.dispatchKeyEvent(event);
    }

    private void checkFinishApp(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                UIUtils.showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                showHome();
                ActivityUtils.finishActivityByAlpha(this);
            }
        }
    }

    private void showHome() {
        BaseFragment baseFragment = null;
        resetTab();
        mHomeTabView.setSelected(true);
        mHomeTabView.setTextColor(getResources().getColor(R.color.color_16));
        mSelfTabView.setTextColor(getResources().getColor(R.color.black9));
        mTitleBarView.setTitleText("酷钱包").setLeftBtnVisibility(View.GONE);
        baseFragment = FragmentFactory.getHomeTabFragment(FragmentFactory.FRAGMENT_HOME_TAB0);
        switchFragment(baseFragment, R.id.fl_activity_home_content);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FragmentFactory.mHomeTabMap.clear();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);


        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:// 音量增大
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume + 1, 1);
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:// 音量减小
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume - 1, 1);
                break;
            case KeyEvent.KEYCODE_BACK:

            default:
                break;
        }

        return true;
//        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GetuiService.class);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (intentResult != null) {
            if (intentResult.getContents() != null) {
                // ScanResult 为获取到的字符串
                long shopId = SharedPreferencesUtils.getLong("master_shop_id", -1);
                String url = intentResult.getContents();
                String qrCode = URLUtils.getValueByName(url, "code");
                ApiManager.getApi().bindQrCode(
                        "HSY001020",
                        AccountDao.getInstance().getAccount().id,
                        qrCode,
                        shopId
                ).enqueue(new NetCallBack<String>() {
                    @Override
                    protected void onSuccess(Call<String> call, Response<String> response) {
                        if (response.body() != null) {
                            UIUtils.showToast("綁定二维码成功");
                            EventBus.getDefault().post(new EventCenter(EventCode.EVENT_CODE_START_LOGIN));
                        } else {
                            UIUtils.showToast("綁定二维码失败");
                        }
                    }

                });
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    public Fragment getVisibleFragment() {
        FragmentManager fragmentManager = HomeActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

}